<template>
  <el-tooltip
    class="item"
    effect="dark"
    :content="text"
    :placement="position"
    :disabled="!show"
  >
    <div
      ref="tooltip"
      class="tooltip-box"
      @mouseover="showTooltip"
      :style="tooltipStyle"
    >
      <!-- 文本显示 -->
      <span style="width: 100%" class="tooltip-text">{{ text }}</span>
    </div>
  </el-tooltip>
</template>
<script>
export default {
  props: {
    // 显示文本
    text: {
      type: String,
      required: true,
    },
    // 宽度
    width: {
      type: [Number, String],
      required: true,
    },
    // 显示位置与element一致
    position: {
      type: String,
      default: "top",
    },
  },
  data() {
    return {
      show: false,
    };
  },
  computed: {
    tooltipStyle() {
      return {
        width:
          (this.width + "").indexOf("%") > -1 ? this.width : `${this.width}px`,
      };
    },
  },
  methods: {
    // 鼠标悬浮检测实际内容是否超出设定宽度
    showTooltip() {
      this.$nextTick(() => {
        if (this.$el.scrollWidth > this.$refs.tooltip.offsetWidth) {
          this.show = true;
        }
      });
    },
  },
  mounted() {},
};
</script>

<style scoped>
.tooltip-box {
  display: inline-block;
  vertical-align: middle;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.tooltip-text {
  cursor: pointer;
}
</style>